<!-- 执行工单详情 -->
<template>
  <div class="view-flex">
    <div>
      <div class="view-equip-title">基础信息</div>
      <ColumnsTable :columns="INSPECTTASKDETAIL_BASEINFO_COLUMNS" :data="baseInfo">
        <template #value="{ scope }">
          <template v-if="scope.prop === 'extendDuration' && (scope.data.extendDuration || scope.data.extendDuration === 0)">
            {{ scope.data.extendDuration }}{{ scope.data.extendDurationUnitDesc }}
          </template>
        </template>
      </ColumnsTable>
    </div>
    <div class="view-mb20">
      <div class="view-equip-title">巡检作业内容</div>
      <px-form
        v-if="baseInfo.inspectRuleAreaDTOList && baseInfo.inspectRuleAreaDTOList.length > 0"
        ref="ruleFormRef"
        :scroll-to-error="true"
        :inline="false"
        :model="formValue"
        label-position="right"
        label-width="80px"
      >
        <px-tabs tab-position="left" class="px-tabs-task-form" @tab-change="handleChangeTab">
          <TabPaneForm
            v-for="(areaItem, areaIndex) in baseInfo.inspectRuleAreaDTOList"
            :key="`${areaItem.inspectArea}${areaIndex}`"
            v-loading="areaLoading"
            :data="formValue[areaIndex]"
            :label="areaItem.inspectAreaDesc"
            :disabled="disabled"
            :activeTab="activeTab"
            :propsValue="[areaIndex]"
            :validated="validated"
            moduleName="ifp-digitaltwins"
          />
        </px-tabs>
      </px-form>
    </div>
    <InspectAlert v-if="baseInfo?.inspectRuleAreaDTOList" v-model="alertVisible" :code="baseInfo.inspectRuleAreaDTOList[activeTab].inspectArea" />
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { INSPECTTASKDETAIL_BASEINFO_COLUMNS } from "../config";
import ColumnsTable from "../../components/ColumnsTable.vue";
import TabPaneForm from "./TabPaneForm.vue";
import InspectAlert from "./InspectAlert.vue";
import type { FormInstance } from "px-ui";
import { queryTaskDetail, queryTaskItem, inspectAreaSignIn } from "@/api/equip/inspectTask";
import { getEnumDefect } from "@/api/defect";
import { useRoute } from "vue-router";
import { PxMessage } from "px-ui";
import { GetInspectTaskRes, TaskFomeValueType } from "../../types";
import { emitter } from "../config/index";
import { useInspectArea, usePrincipal, useTaskInfo } from "../hooks/index";

const alertVisible = ref(false);
const eimts = defineEmits(["handleSave"]);
const props = defineProps(["data", "id", "disabled"]);
const bacicData = defineModel("bacicData");
const activeTab = ref(0);
const {
  query: { id: routeId }
} = useRoute();
const { setInspectArea, getInspectAreaOption } = useInspectArea();
const { getPrincipalList } = usePrincipal();
const { setTaskInfo } = useTaskInfo();
const baseInfo = ref<Partial<GetInspectTaskRes>>({});
const formValue: any = ref<TaskFomeValueType>([]);
const areaLoading = ref(false);
const validated = ref(false);
onMounted(() => {
  getDetail();
  initLevel();
  getInspectAreaOption();
  getPrincipalList();
});
// 获取缺失等级，并通过mitt跨组件传参
const levelOption = ref([]);
const initLevel = async () => {
  if (levelOption.value.length) {
    return setTimeout(() => {
      emitter.emit("levelOptionChange", levelOption.value);
    }, 1000);
  }
  const res: any = await getEnumDefect();
  if (res) {
    const option = Object.keys(res.MISSING_LEVEL).map(key => ({
      label: key,
      value: res.MISSING_LEVEL[key]
    }));
    levelOption.value = option;
    setTimeout(() => {
      emitter.emit("levelOptionChange", option);
    }, 1000);
  }
};
const getDetail = async () => {
  const id = props.id || routeId;
  if (id) {
    const data = await queryTaskDetail(id);
    baseInfo.value = data;
    bacicData.value = data;
    setTaskInfo(data);
    getAreaDetail(0);
  }
};
const getInspectTaskMissDTO = inspectTaskMissDTO => {
  if (inspectTaskMissDTO) {
    return { ...inspectTaskMissDTO, checked: true };
  }
};
const handleChangeTab = async index => {
  if (![6, 7].includes(baseInfo.value?.taskStatus) && formValue.value.length > 0) {
    // 1、切换tab，保存当前数据
    eimts("handleSave", {
      hiddenMessage: true,
      noBack: true,
      index,
      callback: async () => {
        areaLoading.value = true;
        try {
          // 2、保存数据后，获取当前区域最新数据（ps:如异常上报后的ID）
          await getAreaDetail(activeTab.value);
          // 3、获取目标区域最新数据
          await getAreaDetail(index);
          initLevel();
        } catch (error) {}
        areaLoading.value = false;
      }
    });
  }
};
const getAreaDetail = async index => {
  activeTab.value = index;
  // if (formValue.value[index]) {
  //   return;
  // }
  const item = baseInfo.value.inspectRuleAreaDTOList[index];
  setInspectArea(item.inspectArea);
  const data: any = await queryTaskItem({
    taskCode: baseInfo.value.taskCode,
    ruleCode: item.ruleCode,
    inspectArea: item.inspectArea
  });
  if (data) {
    let eqpContentDTOList = null;
    if (data.eqpContentDTOList) {
      eqpContentDTOList = data.eqpContentDTOList.map(item => ({
        ...item,
        inspectTaskMissDTO: getInspectTaskMissDTO(item.inspectTaskMissDTO) || { missingType: "EQP" }
      }));
    }
    formValue.value[index] = {
      taskCode: data.taskCode,
      envContentDTOlist: {
        contentDTOList: data.contentDTOList,
        inspectTaskMissDTO: getInspectTaskMissDTO(data.inspectTaskMissDTO) || { missingType: "ENV" }
      },
      eqpContentDTOList
    };
  }
};

const ruleFormRef = ref<InstanceType<typeof FormInstance>>();
// 表单校验
const validate = (callBack: Function) => {
  ruleFormRef.value.validate(async (valid, errors) => {
    callBack(valid, errors);
    if (!valid) {
      const item: any = Object.values(errors)[0][0];
      const index = Object.keys(errors)[0].split(".")[0];
      const name = baseInfo.value.inspectRuleAreaDTOList[index].inspectAreaDesc;
      PxMessage.error(`${name}——${item.message}`);
    }
  });
};
// 一键签到
const singIn = async () => {
  const index = activeTab.value;
  const item = baseInfo.value.inspectRuleAreaDTOList[index];
  await inspectAreaSignIn({
    taskCode: baseInfo.value.taskCode,
    inspectArea: item.inspectArea
  });
  PxMessage.success("签到成功");
  await getAreaDetail(activeTab.value);
};
defineExpose({
  form: ruleFormRef,
  formValue,
  validated,
  validate,
  singIn,
  showAlert: () => {
    alertVisible.value = true;
  }
});
</script>

<style lang="scss" scoped>
.view-flex {
  position: relative;
  display: flex;
  flex-direction: column;
  // min-height: calc(100vh - 260px);
  margin-bottom: 59px;
  overflow: hidden;

  .view-equip-title {
    height: 22px;
    margin-bottom: 16px;
    font-size: 16px;
    font-weight: bold;
    line-height: 22px;
    color: rgb(0 0 0 / 80%);
  }

  :deep(.inner-tabel) {
    width: 100%;

    .px-table__header thead tr th {
      font-size: 14px;
      font-weight: bold;
      color: #000;
      background-color: #e7eefb !important;
    }

    td.px-table__cell div {
      width: 100%;
    }
  }

  :deep(.px-table__header) {
    .must::before {
      margin-right: 4px;
      color: var(--px-color-danger);
      content: "*";
    }
  }

  :deep(.form-item-in-table) {
    margin-bottom: 0;

    &.px-form-item {
      margin-bottom: 0;
    }
  }

  :deep(.px-tabs__nav-wrap::after) {
    background: rgb(0 0 0 / 10%);
  }

  :deep(.px-tabs-task-form) {
    display: flex;
    height: calc(100vh - 490px);
    overflow: hidden;

    .is-active {
      font-weight: bold;
    }

    .px-tabs__content {
      flex-grow: 1;
      overflow: hidden;
    }

    .px-tab-pane {
      height: 100%;
    }

    .px-form-item {
      align-items: center;
    }

    .px-form-item__label {
      font-weight: 400;
    }
  }
}

.view-task-detail {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  padding: 16px 0;

  .view-task-title {
    display: flex;
    flex-direction: row;
    align-items: center;

    .text {
      margin-left: 20px;
      font-size: 20px;
      font-weight: 600;
      color: rgb(0 0 0 / 90%);
    }

    .status {
      display: flex;
      flex-direction: row;
      align-items: center;

      .circle {
        width: 8px;
        height: 8px;
        margin-right: 5px;
        margin-left: 8px;
        border-radius: 50%;
      }
    }
  }
}

.view-mb20 {
  margin-bottom: 20px;
}
</style>
